package com.googlecode.tidej.shared.model;

public abstract class Artifact implements Comparable<Artifact> {
  protected String name;
  protected String documentation;
  
  protected Artifact(String name) {
    this.name = name;
  }
  
  public String getName() {
    return name;
  }
  
  public String getDocumentation() {
    return documentation;
  }
  
  public void setDocumentation(String s) {
    this.documentation = s;
  }
  
  public String toString() {
    return name;
  }
  
  public String getTitle() {
    return "<b>" + htmlEscape(toString()) + "</b>";
  }
  
  public abstract Library getLibrary();

  public String getQualifiedName() {
    if (getLibrary() == this) {
      return name.replace(' ', '+');
    }
    return getLibrary().getQualifiedName() + "/" + name;
  }
  
  public String getLink() {
    if (getLibrary().getName().equals("hidden") || getLibrary().getName().equals("primitives")) {
      return htmlEscape(getName());
    }
    return "<a href='#" + (getLibrary().isReadOnly() ? "Library/" : "Project/") + htmlEscape(getQualifiedName()) + "'>" + htmlEscape(getName()) + "</a>";
  }

  static String htmlEscape(String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      switch(c) {
      case '<': 
        sb.append("&lt;");
        break;
      case '>': 
        sb.append("&gt;");
        break;
      case '\'': 
        sb.append("&apos;");
        break;
      case '\"': 
        sb.append("&quot;");
        break;
      case '&': 
        sb.append("&amp;");
        break;
      default:
        sb.append(c);
      }
    }
    return sb.toString();
  }
  

  @Override
  public int compareTo(Artifact other) {
    return getName().compareToIgnoreCase(other.getName());
  }
}
